import 'dart:io';

import 'package:dio/dio.dart';
import 'package:find_friend/const/const.dart';
import 'package:shared_preferences/shared_preferences.dart';

part 'network.api.dart';

enum NETWORKHTTPMethod {
   GET,
   POST,
   PUT,
   DELETE
}

class Networktool {

  static String baseURL = APP_IS_RELEASE ? "https://api.zhaotaa.com/" : "http://192.168.0.111/";
  static request(
    String url,
    {
      NETWORKHTTPMethod method = NETWORKHTTPMethod.POST,
      Map<String, dynamic> params,
      Function success, 
      Function(String msg) fail,
      Function finaly
    }) async {
    
    Response response;
    url = baseURL + url;
    print("api = $url, param = $params, method:$method");

    SharedPreferences share = await SharedPreferences.getInstance();
    String token = share.getString(KEY_user_token);

    Options options = Options(receiveTimeout: 1000000);
    if(token != null){
      print("token = $token");
      options = Options(
        headers: {"token": token}
      );
    }

    try {
      switch (method) {
        case NETWORKHTTPMethod.POST:
          FormData formData = FormData.fromMap(params);
          response = await Dio().post(url, data: formData, options: options);
          break;
        case NETWORKHTTPMethod.GET:
          if(params == null) params = {};
          response = await Dio().get(url, queryParameters: params, options: options);
          break;
        case NETWORKHTTPMethod.PUT:
          response = await Dio().put(url, data: params, options: options);
          break;
        case NETWORKHTTPMethod.DELETE:
          response = await Dio().delete(url, data: params,options: options);
          break;
        default:
      }
    } catch (e) {
      if(finaly != null) finaly();
      print(e.toString());
      if(fail != null)fail(e.toString());
    }
    

    if(finaly != null) finaly();
    print("url = $url, data = ${response.data}");
    String code = response.headers.value("statuscode").toString();
    if(code == "200" || code == null) {
      if(success != null) success(response.data);
    } else {
      if(fail != null) {
        if(response.data is Map) {
          fail(response.data["msg"].toString());
        } else {
          fail(response.toString());
        }
      }
    }
  }

  // 下载图片到本地
  static downloadImage(String url, {Function(dynamic) success}) async {
    var response = await Dio().get(url, options: Options(responseType: ResponseType.bytes));
    if(success != null) success(response.data);
  }


  // static downloadFile() async {
  //   var appDocDir = await getTemporaryDirectory();
  //   String savePath = appDocDir.path + "/temp.mp4";
  //   await Dio().download("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4", savePath);
  //   final result = await ImageGallerySaver.saveFile(savePath);
  //   print(result);
  // }


  // 上传多个文件
  static uploads(
    String url, 
    List<File> files, 
    Function success, 
    {NETWORKHTTPMethod method = NETWORKHTTPMethod.POST, 
    Function(String msg) fail, 
    Function finaly
  }) async {

    Response response;
    List<MultipartFile> uploadfiles = [];

    url = baseURL + url;

    for(int i=0;i<files.length;i++) {
      MultipartFile file = await MultipartFile.fromFile(files[i].path);
      uploadfiles.add(file);
    }
    
    

    FormData formData = FormData.fromMap(
      {
        "file":uploadfiles
      }
    );

    SharedPreferences share = await SharedPreferences.getInstance();
    String token = share.getString(KEY_user_token);
    Options options = Options();
    if(token != null){
      print("token = $token"); 
      options = Options(
        headers: {
          "token": token, 
          "Content-Type":"multipart/form-data"
        },
        contentType: "multipart/form-data",
      );
    }
    try{
      response = await Dio().post(url, data: formData, options: options);
      if(finaly != null) finaly();
    } catch(e) {
      if(finaly != null) finaly();
      if(fail != null)fail(e.toString());
      return;
    }
    String code = response.headers.value("statuscode").toString();
    if(code == "200") {
      if(success != null) success(response.data);
    } else {
      if(fail != null) {
        if(response.data is Map) {
          fail(response.data["msg"].toString());
        } else {
          fail(response.toString());
        }
      }
    }
  }

    // 发表文章
  static postArticle(
    String url, 
    Function success, 
    {
      NETWORKHTTPMethod method = NETWORKHTTPMethod.POST, 
      Function(String msg) fail, 
      Function finaly,
      List<File> images, // 发表图片
      List<Map> voices, // 发表图片对应音频
      String recordPath,   // 录音
      int schoolType,    // 本校不可见
      int lovers,       // 情侣身份发布
      int main,         // 不显示再我的主页
      Map<String, dynamic> params, // 
  }) async {

    Response response;
    url = baseURL + url;

    Map<String, dynamic> param = params == null ? {} : params;
    if(images != null) { // 上传的图片
      List<MultipartFile> files = [];
      for(int i=0;i<images.length;i++) {
        MultipartFile file = await MultipartFile.fromFile(images[i].path);
        files.add(file);
      }
      param["images"] = files;
    }

    if(recordPath != null) {
      MultipartFile file = await MultipartFile.fromFile(recordPath);
      param["record"] = [file];
    }

    if(schoolType != null) param["school"] = schoolType;
    if(main != null) param["main"] = main;
    if(lovers != null) param["lovers"] = lovers;

    if(voices != null) {
      List<MultipartFile> files = [];
      for(int i=0;i<voices.length;i++) {
        Map val = voices[i];
        if(val.isNotEmpty){
          MultipartFile file = await MultipartFile.fromFile(val["path"]);
          files.add(file);
        } else {
          files.add(MultipartFile.fromString("",filename: "empty"));
        }
      }
      param["imageVoice"] = files;
    }

    print(url + "param = $param");

    
    FormData formData = FormData.fromMap(param);

    SharedPreferences share = await SharedPreferences.getInstance();
    String token = share.getString(KEY_user_token);
    Options options = Options();
    if(token != null){
      print("token = $token"); 
      options = Options(
        headers: {
          "token": token, 
          "Content-Type":"multipart/form-data"
        },
        contentType: "multipart/form-data",
      );
    }
    try{
      response = await Dio().post(url, data: formData, options: options);
      if(finaly != null) finaly();
    } catch(e) {
      if(finaly != null) finaly();
      if(fail != null)fail(e.toString());
      return;
    }

    String code = response.headers.value("statuscode").toString();
    if(code == "200") {
      if(success != null) success(response.data);
    } else {
      if(fail != null) {
        if(response.data is Map) {
          fail(response.data["msg"].toString());
        } else {
          fail(response.toString());
        }
      }
    }
  }


  // 上传单个文件
  static uploadImage(
    String url, 
    File file, 
    Function success, 
    {NETWORKHTTPMethod method = NETWORKHTTPMethod.POST, 
    Map<String,dynamic> params, 
    Function(String msg) fail, 
    Function finaly
  }) async {
    Response response;
    url = baseURL + url;
    print("api = $url, param = $params");

    SharedPreferences share = await SharedPreferences.getInstance();
    String token = share.getString(KEY_user_token);

    Options options = Options();
    if(params == null) params = {};
    if(token != null){
      print("token = $token"); 
      options = Options(
        headers: {
          "token": token, 
          "Content-Type":"multipart/form-data"
        },
        contentType: "multipart/form-data",
      );
    }

    final fil = await MultipartFile.fromFile(file.path);
    params["file"] = fil;
    FormData formData = FormData.fromMap(params);
    
    try{
      response = await Dio().post(url, data: formData, options: options);
    } catch (e) {
      fail(e.toString());
      return;
    }
    

    if(finaly != null) finaly();

    String code = response.headers.value("statuscode").toString();
    if(code == "200") {
      if(success != null) success(response.data);
    } else {
      if(fail != null) {
        if(response.data is Map) {
          fail(response.data["msg"].toString());
        } else {
          fail(response.toString());
        }
      }
    }
  }
}